import { Button, Card, Form, Input, Select, Space, Table, Tag, message } from 'antd';
import {
  ProFormSelect,
  ProFormDependency,
  ProFormText,
} from '@ant-design/pro-components';
import React, { useState, useRef } from 'react';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import type { Key } from 'antd/lib/table/interface';
import { get, values } from 'lodash';
import { connect } from 'umi';
import FormItem from 'antd/es/form/FormItem';
import { PageContainer } from '@ant-design/pro-layout'
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

const roles = ['辅导员', '班导师', '班长', '团支书'];
const classes = ['电气2301', '电气2302', '电气2303', '电气2304'];
const notifications = [
  '学习计划会议将于明天召开，请准时参加。',
  '本周体育活动推迟至下周，请做好准备。',
  '学校开展环境保护志愿者招募，请有兴趣的同学报名。',
  '各班班长请于本周五参加班长会议。',
  '团委组织乡村义务劳动活动，报名截止本周五。',
  '辅导员将于明天下午在办公室接待同学。',
];

export type TableListItem = {
  key: number;
  stuName: string;
  callNumber: string;
  stuCode: string;
  phoneNumber: string;
  majorLabel: string;
  classLabel: string;
};
//制造假数据
const tableListDataSource: TableListItem[] = [];
for (let i = 0; i < 50; i += 1) {
  tableListDataSource.push({
    key: i,
    stuName: roles[Math.floor(Math.random() * roles.length)],
    stuCode: Math.floor(Math.random() * 1000).toString(),
    callNumber: notifications[Math.floor(Math.random() * notifications.length)],
    phoneNumber: Math.floor(Math.random() * 1000000).toString(),
    majorLabel: "电气",
    classLabel: classes[Math.floor(Math.random() * roles.length)],
  });
}
const columns: ProColumns<TableListItem>[] = [
  {
    title: '序号',
    align: 'center',
    width: 120,
    dataIndex: 'key',
  },
  {
    title: '姓名',
    width: 120,
    align: 'center',
    dataIndex: 'stuName',
  },
  {
    title: '学号',
    width: 120,
    align: 'center',
    dataIndex: 'stuCode',
  },
  {
    title: '专业',
    width: 120,
    align: 'center',
    dataIndex: 'majorLabel',
  },
  {
    title: '班级',
    width: 120,
    align: 'center',
    dataIndex: 'classLabel',
  },
  {
    title: '联系方式',
    width: 120,
    align: 'center',
    dataIndex: 'phoneNumber',
  },
];

const ClusterByGroup: React.FC = (props: any) => {
  // 使用useState钩子创建表格数据源的状态变量tableListData
  const [tableListData, setTableListData] = useState<TableListItem[]>();
  // 使用useState钩子创建状态变量，用于存储用户选择的行的keys
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState("none");
  const [flag, setFlag] = useState(true)
  const [optipnSelect, setOptionSelect] = useState([
    { value: '1', label: '电气工程及其自动化' },
    { value: '2', label: '新能源科学与工程' },
  ])
  const valueSelectList = [{}]
  const onFinish = (values: any) => {
    //console.log('Received values of form:', values);
    let number: number;
    let label: []
    let messageName: string;
    if (form.getFieldValue("number") && form.getFieldValue("majorLabel") && form.getFieldValue("messageName")) {
      number = form.getFieldValue("number")
      label = form.getFieldValue("majorLabel")
      messageName = form.getFieldValue("messageName")
      if (props.dispatch) {
        //console.log("新建分群")
        props.dispatch({
          //路径：model的namespace+effects函数名
          type: 'Model_Counsellor/setGroupByGroupEffects',
          payload: {
            clusterType: number,
            label: label,
            clusterLabel: messageName,
            teacherCode: localStorage.getItem('userAccount')
          },
        });
      }
    }
    else if (form.getFieldValue("number") && form.getFieldValue("classLabel") && form.getFieldValue("messageName")) {
      number = form.getFieldValue("number")
      label = form.getFieldValue("classLabel")
      messageName = form.getFieldValue("messageName")
      if (props.dispatch) {
        //console.log("新建分群")
        props.dispatch({
          //路径：model的namespace+effects函数名
          type: 'Model_Counsellor/setGroupByGroupEffects',
          payload: {
            clusterType: number,
            label: label,
            clusterLabel: messageName,
            teacherCode: localStorage.getItem('userAccount')
          },
        });
      }
    }
  };

  const getList = () => {
    let number: number;
    let label: []
    if (form.getFieldValue("number") == 1 && form.getFieldValue("majorLabel")) {
      number = form.getFieldValue("number")
      label = form.getFieldValue("majorLabel")
      if (props.dispatch) {
        //console.log("预览分群")
        props.dispatch({
          //路径：model的namespace+effects函数名
          type: 'Model_Counsellor/getStudentListforGroupEffects',
          payload: {
            data: {
              clusterType: number,
              label: label,
            },
            callback: (value: any) => {
              //console.log(value)
              setTableListData(value)
            },
          },
        });
      }
    }
    else if (form.getFieldValue("number") == 2 && form.getFieldValue("classLabel")) {
      number = form.getFieldValue("number")
      label = form.getFieldValue("classLabel")
      if (props.dispatch) {
        //console.log("预览分群")
        props.dispatch({
          //路径：model的namespace+effects函数名
          type: 'Model_Counsellor/getStudentListforGroupEffects',
          payload: {
            data: {
              clusterType: number,
              label: label,
            },
            callback: (value: any) => {
              //console.log(value)
              setTableListData(value)
            },
          },
        });
      }
    } else message.warn("请选择相应选项")
    setLoading(" ")
  };
  const getOptions = (vales: any) => {
    if (flag) {
      if (props.dispatch) {
        //console.log("预览分群")
        props.dispatch({
          //路径：model的namespace+effects函数名
          type: 'Model_Counsellor/getOptionsEffects',
          payload: {
            callback: (value: any) => {
              if (vales == "1")
                selectValue(value.majorLabel)
              else if (vales == "2")
                selectValue(value.classLabel)
            },
          },
        });
      }
    }
    setFlag(false)
  }
  const selectValue = (values: any) => {
    let i = 0
    values.forEach(item => {
      let selectGroup = {
        value: i.toString,
        label: item

      }
      i++
      valueSelectList.push(selectGroup)
    })
    valueSelectList.splice(0, 1)
    setOptionSelect(valueSelectList)
  }
  return (
    <PageContainer>
      <Card title="新建分群" bordered={false}>
        <Form
          form={form}
          name="dynamic_form_complex"
          onFinish={onFinish}
          style={{ maxWidth: 400 }}
          autoComplete="off"
        >
          <Form.Item>
            <ProFormText
              name="messageName"
              label="分群名称"
              width="md"
              placeholder="请输入名称"
              rules={[{ required: true }]}
            />
          </Form.Item>
          <Form.Item>
            <ProFormSelect
              onChange={() => { setFlag(true) }}
              name={['number']}
              label="分群方式"
              width="lg"
              rules={[
                {
                  required: true,
                },
              ]}
              options={
                [
                  { value: '1', label: '专业' },
                  { value: '2', label: '班级' },
                ]
              }
            />
          </Form.Item>
          <Form.Item>
            <ProFormDependency name={[['number']]}>
              {({ number }) => {
                if (
                  number == '1'
                ) {
                  getOptions(number)
                  return (
                    <ProFormSelect
                      mode="multiple"
                      width="lg"
                      name='majorLabel'
                      rules={[{ required: true, message: '请选择专业' }]}
                      label="专业名称"
                      options={optipnSelect}
                      placeholder="请选择专业"
                    />
                  );
                } else if (
                  number == '2'
                ) {
                  getOptions(number)
                  return (
                    <ProFormSelect
                      mode="multiple"
                      width="lg"
                      name='classLabel'
                      rules={[{ required: true, message: '请选择班级' }]}
                      label="班级名称"
                      options={optipnSelect}
                      placeholder="请选择班级"
                    />
                  );
                }
              }}
            </ProFormDependency>
          </Form.Item>
          <Form.Item>
            <Space size={'middle'}>
              <Button type="primary" style={{ width: 120 }} onClick={getList} >
                预览分群人名单
              </Button>
              <Button type="primary" htmlType="submit" style={{ width: 120 }}>
                确认
              </Button>
              <Button type="primary" onClick={() => { history.push("./list"), window.location.reload() }}>返回分群列表</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card>
        <div style={{ display: loading }}>
          <ProCard title="分群预览">
            <ProTable<TableListItem>
              columns={columns}
              //配置表格的行选择功能。
              rowSelection={{
                selectedRowKeys, // 设置用户选择的行
                onChange: (keys) => setSelectedRowKeys(keys), // 更新用户选择的行
                selections: [
                  Table.SELECTION_ALL, //全选
                  Table.SELECTION_INVERT, //反选
                  Table.SELECTION_NONE, //全不选
                ],
              }}
              //自定义表格顶部的操作选项，通常用于添加自定义操作按钮。
              tableAlertOptionRender={() => {
                return (
                  <Space size={16}>
                    <a>导出数据</a>
                  </Space>
                );
              }}
              dataSource={tableListData}
              options={false}
              search={false}
              pagination={{
                //分页
                pageSize: 10,
              }}
              rowKey="key"
            />
          </ProCard>
        </div>
      </Card>
    </PageContainer>

  );
};

export default connect(({ Model_Counsellor }: any) => ({
  Model_Counsellor,
}))(ClusterByGroup);
